package com.hifar.plugins;

import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.tssk.kylx.fw.utils.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 * @Description 签名渲染插件（为图片时，渲染图片,负责为文本）
 * @Author zhuWeiWei
 * @Date 2024/1/29 11:43
 */
public class SignRenderPolicy extends AbstractRenderPolicy<Object> {

    // 宽
    private int width;
    // 高
    private int height;

    private boolean diyStyle;

    @Override
    public void doRender(RenderContext<Object> context) throws Exception {
        Object data = context.getData();
        XWPFRun run = context.getRun();
        if ("null".equals(data)) {
            run.setText("");
            return;
        }
        if (StringUtils.isEmpty(data)) {
            return;
        }
        boolean isImg = isImg(data);
        if (isImg) {
            PictureRenderData renderData = wrapper(data);
            PictureRenderPolicy.Helper.renderPicture(run, renderData);
            return;
        }
        run.setText(StringUtils.trimNull(data));
    }


    @Override
    protected void afterRender(RenderContext<Object> context) {
        Object data = context.getData();
        if (StringUtils.isNotEmpty(data)) {
            this.clearPlaceholder(context, false);
        }
    }

    private PictureRenderData wrapper(Object object) {
        if (this.diyStyle) {
            return Pictures.of(object.toString()).size(this.width, this.height).create();
        }
        return object instanceof PictureRenderData ? (PictureRenderData) object : Pictures.of(object.toString()).fitSize().create();
    }

    private boolean isImg(Object object) {
        if (object instanceof PictureRenderData) {
            return true;
        }
        String imgUrl = StringUtils.trimNull(object);
        if (StringUtils.isEmpty(imgUrl) || "null".equals(imgUrl)) {
            return false;
        }
        // 支持多种URL格式：http/https、相对路径、包含文件扩展名
        return imgUrl.startsWith("http") || 
               imgUrl.startsWith("https") || 
               imgUrl.startsWith("/") ||
               (imgUrl.contains(".") && isValidImageExtension(imgUrl));
    }
    
    /**
     * 验证是否为有效的图片文件扩展名
     */
    private boolean isValidImageExtension(String url) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"};
        String lowerUrl = url.toLowerCase();
        for (String ext : imageExtensions) {
            if (lowerUrl.contains(ext)) {
                return true;
            }
        }
        return false;
    }


    public SignRenderPolicy() {
    }

    public SignRenderPolicy(int width, int height) {
        this.width = width;
        this.height = height;
        this.diyStyle = true;
    }

}
